package com.my.yc.d0304;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.*;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    public static List<Map<String, Date>> onlineUsers = new ArrayList<>();

    public OnlineListener() {
    }



    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is added to a session. */
        sbe.getName();  // 添加到会话中的属性名 => loginedUser
        sbe.getValue(); // 添加到会话中的属性值
        if (sbe.getName().equals("loginedUser")){
            onlineUsers.add((Map<String, Date>) sbe.getValue());
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is removed from a session. */
        if (sbe.getName().equals("loginedUser")){
            onlineUsers.remove((Map<String, Date>) sbe.getValue());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        if (sbe.getName().equals("loginedUser")){
            Map<String, Date> loginedUser = (Map<String, Date>) sbe.getSession().getAttribute("loginedUser");
            // 移除原来的名字
            onlineUsers.remove((Map<String, Date>) sbe.getValue());
            // 添加新的名字
            onlineUsers.add(loginedUser);
        }
    }
}
